import { useState, useEffect } from "react";
import { useModel } from "umi";
import { Form, Input, Select, Button, message, Space, Cascader, Row, Col, Dropdown } from "antd";
import { useReactive } from "ahooks";
import { DownOutlined } from "@ant-design/icons";

import useAreaCode from "../../hooks/useAreaCode";
import useStaff from "../../hooks/staff/useStaff";
import userCheckStoreNameNoSelf from "../../hooks/store/userCheckStoreNameNoSelf";
import useUpdateStore from "../../hooks/store/useUpdateStore";
import useAllAffiliates from "../../hooks/affiliate/useAllAffiliates";

const EditStoreForm = ({ oiType, store, reloadData }) => {
    const { onCloseGlobalModal } = useModel("global.modal");
    const { loadAreaData, areas } = useAreaCode();

    const { loading: staffLoading, staffs } = useStaff({});

    const { checkStoreNameNoSelf } = userCheckStoreNameNoSelf();
    const { updateStore } = useUpdateStore();
    const { loading: affiliateLoading, loadAllAffiliates, affiliates } = useAllAffiliates();

    const [form] = Form.useForm();

    const [selectedOfficeLocation, setSelectedOfficeLocation] = useState([]);

    const state = useReactive({
        loading: false,
        maInfo: store.maInfo || {},
        asInfo: store.asInfo || {},
    });

    useEffect(() => {
        const { oiZoja } = store;
        setSelectedOfficeLocation(oiZoja);
        let areasCache = globalAreaCode["0"].map((item) => {
            if (item.id === oiZoja[0].id) {
                return {
                    ...item,
                    isLeaf: false,
                    level: 1,
                    children: globalAreaCode[item.id].map((item1) => {
                        if (item1.id === oiZoja[1].id) {
                            return {
                                ...item1,
                                isLeaf: false,
                                level: 2,
                                children: globalAreaCode[item1.id].map((item2) => {
                                    if (item2.id === oiZoja[2].id) {
                                        return {
                                            ...item2,
                                            isLeaf: false,
                                            level: 3,
                                            children: globalAreaCode[item2.id].map((item3) => ({ ...item3, isLeaf: true, level: 4 })),
                                        };
                                    }
                                    return { ...item2, isLeaf: false, level: 3 };
                                }),
                            };
                        }
                        return { ...item1, isLeaf: false, level: 2 };
                    }),
                };
            }
            return { ...item, isLeaf: false, level: 1 };
        });
        state.areas = areasCache;
    }, []);

    let onFinish = async (values) => {
        values.oiUuid = store.oiUuid;
        values.maInfo = state.maInfo || {};
        values.asInfo = state.asInfo || {};
        values.oiZoja = selectedOfficeLocation.map((item) => ({ id: item.id, text: item.text }));

        let affiliate = affiliates.find((item) => item.oaName === values.ptInfo?.oaName);
        values.ptInfo = affiliate ? { ...values.ptInfo, ...affiliate } : values.ptInfo;

        let res = await updateStore(values);

        if (res) {
            form.resetFields();
            message.success("成功更新门店信息");
            reloadData();
            onCloseGlobalModal();
        }
    };

    const oiNameValidator = async (rule, value) => {
        if (value && validates.titleAndName(value) && value.length < 31) {
            let res = await checkStoreNameNoSelf({ oiName: value, notEqualTo: store.oiUuid });
            if (res === null) return Promise.reject("检查门店名称出错");
            return res > 0 ? Promise.reject("门店名称重复！") : Promise.resolve();
        } else {
            return Promise.reject("门店名称只能输入中文、英文、数字，最多30个汉字");
        }
    };

    const onOfficeLocationChange = (value, selectedOptions) => {
        setSelectedOfficeLocation(selectedOptions);
    };

    const { oiZoja, maInfo, asInfo } = store;

    const initialValues = {
        ...store,
        maInfo: maInfo?.osUuid || undefined,
        asInfo: asInfo?.osUuid || undefined,
        oiZoja: oiZoja.map((item) => item.id),
    };

    return (
        <Form form={form} layout="vertical" onFinish={onFinish} initialValues={initialValues}>
            {oiType === "合作门店" && (
                <Row gutter={10}>
                    <Col span={18}>
                        <Form.Item label="合作组织名称" name={["ptInfo", "oaName"]} validateTrigger="onBlur" rules={[{ required: true }]}>
                            <Input placeholder="请输入" allowClear />
                        </Form.Item>
                    </Col>
                    <Col span={6}>
                        <Dropdown
                            menu={{
                                items: affiliates.map((item) => ({ label: item.oaName, key: item.oaName })),
                                onClick: ({ key }) => form.setFieldsValue({ ptInfo: { oaName: key } }),
                            }}
                            trigger={["click"]}
                            disabled={!affiliates || affiliates.length === 0}
                        >
                            <Button icon={<DownOutlined />} disabled={!affiliates || affiliates.length === 0} style={{ marginTop: 30 }}>
                                选择关联组织
                            </Button>
                        </Dropdown>
                    </Col>
                </Row>
            )}

            {oiType === "合作门店" && (
                <Row gutter={10}>
                    <Col span={12}>
                        <Form.Item label="联系人" name={["ptInfo", "contactName"]} rules={[{ required: true }]}>
                            <Input placeholder="请输入" />
                        </Form.Item>
                    </Col>
                    <Col span={12}>
                        <Form.Item label="联系电话" name={["ptInfo", "contactPhone"]} rules={[{ required: true }]}>
                            <Input placeholder="请输入" />
                        </Form.Item>
                    </Col>
                </Row>
            )}

            <Row gutter={10}>
                <Col span={18}>
                    <Form.Item label="门店名称" name="oiName" validateTrigger="onBlur" rules={[{ required: true, validator: oiNameValidator }]}>
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
                <Col span={6}>
                    <Form.Item label="联系电话" name="oiPhon">
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
            </Row>

            <Row gutter={10}>
                <Col span={12}>
                    <Form.Item label="负责人(店长)" name="maInfo" rules={[{ required: true }]}>
                        <Select
                            loading={staffLoading}
                            placeholder="请选择"
                            options={staffs}
                            fieldNames={{ label: "osName", value: "osUuid" }}
                            onChange={(value, option) => (state.maInfo = { osUuid: option.osUuid, osName: option.osName })}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="管理人" name="asInfo">
                        <Select
                            loading={staffLoading}
                            placeholder="请选择"
                            options={staffs}
                            fieldNames={{ label: "osName", value: "osUuid" }}
                            onChange={(value, option) => (state.asInfo = { osUuid: option.osUuid, osName: option.osName })}
                        />
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item label="所在地区" name="oiZoja" rules={[{ required: true, message: "请选择门店所在地" }]}>
                <Cascader placeholder="请选择" options={state.areas} loadData={loadAreaData} onChange={onOfficeLocationChange} fieldNames={{ label: "text", value: "id" }} />
            </Form.Item>

            <Row gutter={10}>
                <Col span={12}>
                    <Form.Item label="所在社区" name="oiComm">
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="所在小区" name="oiEsta">
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item label="详细地址" name="oiAddr">
                <Input placeholder="请输入" />
            </Form.Item>

            <Row gutter={10}>
                <Col span={12}>
                    <Form.Item label="地图经度" name="radius">
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item label="地图纬度" name="latitude">
                        <Input placeholder="请输入" />
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item label="职能说明" name="oiDesc">
                <Input.TextArea placeholder="请输入" />
            </Form.Item>

            <div style={{ marginTop: 20, textAlign: "center" }}>
                <Space>
                    <Button loading={state.loading} type="primary" htmlType="submit" style={{ width: "100%" }}>
                        提交
                    </Button>
                    <Button loading={state.loading} onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </div>
        </Form>
    );
};

export default EditStoreForm;
